import { useEffect, useState, useRef } from 'react';
import { Link } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeHighlight from 'rehype-highlight';
import rehypeRaw from 'rehype-raw';
import { ArrowLeft, List, ChevronRight } from 'lucide-react';
import { useLanguage, useLocalizedLink } from '@kernelproxy/i18n';
import 'highlight.js/styles/github.css';
import 'highlight.js/styles/github-dark.css';

interface TocItem {
  id: string;
  text: string;
  level: number;
}

const PrivacyPolicy = () => {
  const [content, setContent] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [toc, setToc] = useState<TocItem[]>([]);
  const [activeId, setActiveId] = useState<string>('');
  const [tocOpen, setTocOpen] = useState(false);
  const { language } = useLanguage();
  const { getLink } = useLocalizedLink();
  const articleRef = useRef<HTMLElement>(null);

  useEffect(() => {
    const loadMarkdown = async () => {
      try {
        setLoading(true);
        
        let mdPath = '/legal/privacy-policy.md';
        if (language === 'zh-CN') {
          try {
            const zhResponse = await fetch('/legal/privacy-policy.zh-CN.md');
            if (zhResponse.ok) {
              mdPath = '/legal/privacy-policy.zh-CN.md';
            }
          } catch (e) {
            // Use default version
          }
        }

        const response = await fetch(mdPath);
        if (!response.ok) {
          throw new Error('Privacy Policy not found');
        }
        const text = await response.text();
        setContent(text);
        extractToc(text);
      } catch (err) {
        console.error('Error loading markdown:', err);
        setContent(language === 'zh-CN' ? '# 隐私政策\n\n加载失败，请稍后重试。' : '# Privacy Policy\n\nFailed to load. Please try again later.');
      } finally {
        setLoading(false);
      }
    };

    loadMarkdown();
  }, [language]);

  const extractToc = (markdown: string) => {
    const headingRegex = /^(#{1,3})\s+(.+)$/gm;
    const items: TocItem[] = [];
    let match;

    while ((match = headingRegex.exec(markdown)) !== null) {
      const level = match[1].length;
      const text = match[2].replace(/\[([^\]]+)\]\([^)]+\)/g, '$1');
      const id = text
        .toLowerCase()
        .replace(/[^\w\s-]/g, '')
        .replace(/\s+/g, '-');
      
      items.push({ id, text, level });
    }

    setToc(items);
  };

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setActiveId(entry.target.id);
          }
        });
      },
      { rootMargin: '-100px 0px -66%' }
    );

    if (articleRef.current) {
      const headings = articleRef.current.querySelectorAll('h1, h2, h3');
      headings.forEach((heading) => observer.observe(heading));
    }

    return () => observer.disconnect();
  }, [content]);

  const scrollToSection = (id: string) => {
    const element = document.getElementById(id);
    if (element) {
      const offset = 100;
      const elementPosition = element.getBoundingClientRect().top;
      const offsetPosition = elementPosition + window.pageYOffset - offset;

      window.scrollTo({
        top: offsetPosition,
        behavior: 'smooth'
      });
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#00d4ff]"></div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 transition-colors duration-300">
      {/* Header */}
      <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 sticky top-0 z-40 backdrop-blur-sm bg-white/90 dark:bg-gray-800/90">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <Link 
              to={getLink('/login')} 
              className="flex items-center text-gray-600 dark:text-gray-300 hover:text-[#00d4ff] transition-colors"
            >
              <ArrowLeft size={20} className="mr-2" />
              <span>{language === 'zh-CN' ? '返回登录' : 'Back to Login'}</span>
            </Link>
            
            <button
              onClick={() => setTocOpen(!tocOpen)}
              className="md:hidden flex items-center text-gray-600 dark:text-gray-300 hover:text-[#00d4ff] transition-colors"
            >
              <List size={20} className="mr-2" />
              <span>{language === 'zh-CN' ? '目录' : 'Table of Contents'}</span>
            </button>
          </div>
        </div>
      </div>

      <div className="container mx-auto px-4 py-8">
        <div className="flex gap-8">
          {/* Main Content */}
          <article 
            ref={articleRef}
            className="flex-1 bg-white dark:bg-gray-800 rounded-lg shadow-lg p-8 lg:p-12 max-w-4xl mx-auto lg:mx-0 transition-colors duration-300"
          >
            <ReactMarkdown
              remarkPlugins={[remarkGfm]}
              rehypePlugins={[rehypeHighlight, rehypeRaw]}
              components={{
                h1: ({ node, ...props }) => {
                  const text = props.children?.toString() || '';
                  const id = text.toLowerCase().replace(/[^\w\s-]/g, '').replace(/\s+/g, '-');
                  return <h1 id={id} className="text-4xl font-bold text-gray-900 dark:text-white mb-6 pb-4 border-b-2 border-[#00d4ff]" {...props} />;
                },
                h2: ({ node, ...props }) => {
                  const text = props.children?.toString() || '';
                  const id = text.toLowerCase().replace(/[^\w\s-]/g, '').replace(/\s+/g, '-');
                  return <h2 id={id} className="text-3xl font-bold text-gray-900 dark:text-white mt-12 mb-4" {...props} />;
                },
                h3: ({ node, ...props }) => {
                  const text = props.children?.toString() || '';
                  const id = text.toLowerCase().replace(/[^\w\s-]/g, '').replace(/\s+/g, '-');
                  return <h3 id={id} className="text-2xl font-semibold text-gray-800 dark:text-gray-200 mt-8 mb-3" {...props} />;
                },
                p: ({ node, ...props }) => <p className="text-gray-700 dark:text-gray-300 mb-4 leading-relaxed" {...props} />,
                ul: ({ node, ...props }) => <ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mb-4 space-y-2" {...props} />,
                ol: ({ node, ...props }) => <ol className="list-decimal list-inside text-gray-700 dark:text-gray-300 mb-4 space-y-2" {...props} />,
                li: ({ node, ...props }) => <li className="ml-4" {...props} />,
                a: ({ node, ...props }) => <a className="text-[#00d4ff] hover:underline" {...props} />,
                strong: ({ node, ...props }) => <strong className="font-bold text-gray-900 dark:text-white" {...props} />,
                table: ({ node, ...props }) => (
                  <div className="overflow-x-auto my-6">
                    <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700 border border-gray-200 dark:border-gray-700" {...props} />
                  </div>
                ),
                thead: ({ node, ...props }) => <thead className="bg-gray-50 dark:bg-gray-900" {...props} />,
                th: ({ node, ...props }) => <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider" {...props} />,
                td: ({ node, ...props }) => <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300" {...props} />,
              }}
            >
              {content}
            </ReactMarkdown>
          </article>

          {/* Table of Contents - Desktop */}
          {toc.length > 0 && (
            <aside className={`hidden lg:block w-64 sticky top-24 self-start ${tocOpen ? 'block' : 'hidden'} md:block`}>
              <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 transition-colors duration-300 max-h-[calc(100vh-120px)] flex flex-col">
                <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-4 flex items-center flex-shrink-0">
                  <List size={20} className="mr-2" />
                  {language === 'zh-CN' ? '目录' : 'Table of Contents'}
                </h3>
                <nav className="space-y-2 overflow-y-auto pr-2 scrollbar-thin scrollbar-thumb-gray-300 dark:scrollbar-thumb-gray-600 scrollbar-track-transparent">
                  {toc.map((item) => (
                    <button
                      key={item.id}
                      onClick={() => scrollToSection(item.id)}
                      className={`block w-full text-left py-1 px-2 rounded transition-colors ${
                        activeId === item.id
                          ? 'bg-[#00d4ff]/10 text-[#00d4ff] font-medium'
                          : 'text-gray-600 dark:text-gray-400 hover:text-[#00d4ff] hover:bg-gray-100 dark:hover:bg-gray-700'
                      }`}
                      style={{ paddingLeft: `${(item.level - 1) * 12 + 8}px` }}
                    >
                      <span className="flex items-center text-sm">
                        {item.level > 1 && <ChevronRight size={14} className="mr-1 flex-shrink-0" />}
                        <span className="line-clamp-2">{item.text}</span>
                      </span>
                    </button>
                  ))}
                </nav>
              </div>
            </aside>
          )}
        </div>
      </div>

      {/* Mobile TOC Modal */}
      {tocOpen && (
        <div className="md:hidden fixed inset-0 bg-black bg-opacity-50 z-50" onClick={() => setTocOpen(false)}>
          <div className="bg-white dark:bg-gray-800 w-80 h-full overflow-y-auto p-6" onClick={(e) => e.stopPropagation()}>
            <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-4">
              {language === 'zh-CN' ? '目录' : 'Table of Contents'}
            </h3>
            <nav className="space-y-2">
              {toc.map((item) => (
                <button
                  key={item.id}
                  onClick={() => {
                    scrollToSection(item.id);
                    setTocOpen(false);
                  }}
                  className={`block w-full text-left py-2 px-3 rounded ${
                    activeId === item.id
                      ? 'bg-[#00d4ff]/10 text-[#00d4ff] font-medium'
                      : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700'
                  }`}
                  style={{ paddingLeft: `${(item.level - 1) * 12 + 12}px` }}
                >
                  {item.text}
                </button>
              ))}
            </nav>
          </div>
        </div>
      )}
    </div>
  );
};

export default PrivacyPolicy;
